<template>
	<div>
		<!--		顶部区域-->
		<el-row class="top">
			<el-col :span="24">
				<el-form :inline="true" :model="state.queryFrom">
					<el-form-item label="商品编号：">
						<el-input v-model="state.queryFrom.id" placeholder="产品编号" clearable />
					</el-form-item>
					<el-form-item label="产品名称：">
						<el-input v-model="state.queryFrom.name" placeholder="产品名称" clearable />
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="init()">查询</el-button>
					</el-form-item>
				</el-form>
			</el-col>
		</el-row>


		<!--		内容区域-->
		<el-row>
			<el-col :span="24">
				<el-tabs v-model="state.activeName" @tab-change="handleClick">
					<el-tab-pane v-for="item in state.tabPaneList" :label="item" :name="item">
						<el-table :data="state.tableData" border style="width: 100%">
							<el-table-column type="expand">
								<template #default="props">
									<div style="margin-left: 10px">
										<el-descriptions title="" border :column="2">

											<el-descriptions-item label="产品分类">{{ props.row.productCate }}</el-descriptions-item>
											<el-descriptions-item label="产品标签">
												<el-tag size="small">{{ props.row.productTag }}</el-tag>
											</el-descriptions-item>
											<el-descriptions-item label="折扣比例">{{ props.row.priceAccreditRate * 10 }}折
											</el-descriptions-item>
											<el-descriptions-item label="佣金金额">{{ props.row.commission }}元</el-descriptions-item>

											<el-descriptions-item label="点赞数">{{ props.row.praiseNum }}</el-descriptions-item>
											<el-descriptions-item label="下载数">{{ props.row.downNum }}</el-descriptions-item>
										</el-descriptions>
									</div>
								</template>
							</el-table-column>
							<el-table-column prop="productId" label="商品编号" align="center" width="120" />
							<el-table-column prop="productName" label="产品名称" align="center" />
							<el-table-column prop="productImg" label="封面图" align="center">
								<template #default="props">
									<el-image
										:src="addProtocol(props.row.productImg)"
										:zoom-rate="1.2"
										:max-scale="7"
										:min-scale="0.2"
										:preview-src-list="[props.row.productImg]"
										:preview-teleported="true"
										fit="fill"
									/>
								</template>
							</el-table-column>
							<el-table-column prop="priceCurrentPrice" label="基础价格" align="center" />
							<el-table-column prop="priceDeploy" label="指导价格" align="center" />
							<el-table-column prop="priceGuide" label="全套价格" align="center" />
							<el-table-column prop="priceAccreditPrice" label="视频" align="center">
								<template #default="props">
									<el-row justify="space-around">
										<el-col :span="12">
											<el-icon size="16" @click="video(props.row)" style="cursor: pointer">
												<VideoCamera />
											</el-icon>
										</el-col>
										<el-col :span="6">
											<el-icon size="16" @click="bzImps(props.row)" style="cursor: pointer">
												<Paperclip />
											</el-icon>
										</el-col>
									</el-row>
								</template>

							</el-table-column>
							<el-table-column label="详情操作" align="center" width="180">
								<template #default="props">
									<el-button size="small" link type="primary" @click="userInfo(props.row.adminCusUser)">用户信息
									</el-button>
									<el-button size="small" link type="primary" @click="info(props.row.productDesc)">商品描述</el-button>
									<el-button size="small" link type="primary" @click="info(props.row.productDesc)"></el-button>
								</template>
							</el-table-column>
							<el-table-column label="操作" min-width="120" align="center">
								<template #default="props">
									<el-button size="small" link type="primary" @click="document(props.row)">添加文档</el-button>
									<el-button size="small" v-if="props.row.productIsPutaway === 1" link type="primary"
														 @click="offShelf(props.row,0)">下架
									</el-button>
									<el-button size="small" v-if="props.row.productIsPutaway === 0" link type="primary"
														 @click="offShelf(props.row,1)">上架
									</el-button>
									<el-button size="small" v-if="props.row.productIsPutaway === 0" link type="primary"
														 @click="updataPrice(props.row)">价格调整
									</el-button>
									<el-button size="small" v-if="props.row.productIsPutaway === 0" link type="primary"
														 @click="to(props.row.productId)">修改
									</el-button>
									<el-popconfirm v-if="props.row.productIsPutaway === 0" title="你确定要删除商品吗"
																 @confirm="del(props.row)">
										<template #reference>
											<el-button link type="primary">删除</el-button>
										</template>
									</el-popconfirm>
								</template>
							</el-table-column>
						</el-table>
						<div class="pagination-container">
							<el-pagination
								:page-size="state.pageValidate.pageSize"
								layout="prev, pager, next"
								:total="state.total"
								@current-change="handleCurrentChange"
							/>
						</div>
					</el-tab-pane>

				</el-tabs>
			</el-col>
		</el-row>
		<el-dialog
			v-model="state.infoDialogVisible"
			title="商品详情"
			width="50%"
			:before-close="handleClose"
		>
			<v-md-preview :text="state.infoDesc" height="400px"></v-md-preview>
		</el-dialog>
		<el-dialog v-model="state.userInfoDialogVisible"
							 title="用户信息"
							 width="800">
			<el-descriptions :title="state.userInfo.nickName">
				<el-descriptions-item label="用户编号">{{ state.userInfo.id }}</el-descriptions-item>
				<el-descriptions-item label="手机号">{{ state.userInfo.cellPhone }}</el-descriptions-item>
				<el-descriptions-item label="角色">
					<el-tag size="small"> {{ state.userInfo.isAccredit === 1 ? '授权商' : '普通用户' }}</el-tag>
				</el-descriptions-item>
			</el-descriptions>
		</el-dialog>
		<el-dialog
			width="500"
			v-model="state.dialogVideoVisible"
			title="上传视频">
			<div style="height: 240px;width: 100%;margin: 0 auto;margin-bottom: 10px">
				<el-upload
					drag
					:action="`${state.imgPath}1`"
					multiple
					:limit="1"
					accept=".mp4"
					:on-success="videoHandleSuccess"
				>
					<el-icon class="el-icon--upload">
						<Plus />
					</el-icon>
					<div class="el-upload__text">点击或拖拽文件到此处上传</div>
					<div class="el-upload__text">支持MP4</div>
					<template #tip>
						<div class="el-upload__tip" style="color: #FF0000">
							{{ state.updateFrom.url === null ? '商品没有上传视频！' : '商品已经上传视频！' }}
						</div>
					</template>
				</el-upload>
			</div>

				<vue3VideoPlay v-bind="options" :src="state.updateFrom.url"/>

			<template #footer>
                  <span class="dialog-footer">
                    <el-button type="primary" @click="updataFile">确定 新增/更换视频</el-button>
                  </span>
			</template>
		</el-dialog>
		<el-dialog v-model="state.dialogBzImpsVisible" title="B站引入地址">
			<el-input
				style="margin-bottom: 10px"
				v-model="state.bzImpsFrom.bzImps"
				:rows="5"
				type="textarea"
				placeholder="请输入B站引入地址"
			/>
			<div style="width: 100%;height: 320px;">
				<div v-html="state.bzImpsFrom.bzImps"></div>
			</div>
			<template #footer>
                  <span class="dialog-footer">
                    <el-button type="primary" @click="updataBzImps">新增/更换视频</el-button>
                  </span>
			</template>
		</el-dialog>
		<!--		文档上传弹窗-->
		<el-dialog
			v-model="state.docDialogVisible"
			title="文档上传"
			width="1000"
			:close-on-click-modal="true"
			:close-on-press-escape="true"
			draggable
		>
			<el-row :gutter="20">
				<el-col :span="14">
					<!--					列表-->
					<el-table :data="state.documentList" style="width: 100%">
						<el-table-column prop="fileName" label="名称" />
						<el-table-column prop="createTime" label="上传时间" width="180" />
						<el-table-column label="操作" width="140">
							<template #default="scope">
								<el-button link type="primary" size="small" @click.stop="view(scope.row.fileUrl)">查看</el-button>
								<el-button link type="primary" size="small" @click.stop="download(scope.row.fileUrl)">下载</el-button>
								<el-button link type="primary" size="small" @click="delDoc(scope.row)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-col>
				<el-col :span="10">
					<el-form :model="state.docFrom" label-width="auto" style="max-width: 600px">
						<el-form-item>
							<el-upload
								class="doc-upload"
								drag
								:action="`${state.imgPath}6`"
								multiple
								:on-success="docHandleSuccess"
								:show-file-list="false"
								accept=".pdf,.doc,.docx,ppt,.exec"
								:limit="1"
							>
								<el-icon class="el-icon--upload">
									<upload-filled />
								</el-icon>
								<div class="el-upload__text">将文件拖放到此处或 <em>点击上传</em></div>
							</el-upload>
						</el-form-item>
						<el-form-item>
							<el-input v-model="state.docFrom.name" placeholder="请输入文件名称" />
						</el-form-item>
					</el-form>
				</el-col>
			</el-row>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="docBtn">提交</el-button>
				</div>
			</template>
		</el-dialog>
		<!--		修改价格弹窗-->
		<el-dialog
			v-model="state.priceDialogVisible"
			title="修改价格弹窗"
			width="500"
		>
			<el-form
				ref="ruleFormRef"
				:rules="rules"
				:model="state.priceFrom"
				label-width="auto"
				style="max-width: 600px">
				<el-form-item label="基础价格" prop="priceCurrentPrice">
					<el-input-number v-model="state.priceFrom.priceCurrentPrice" :precision="2" :step="0.1" :max="5000" />

				</el-form-item>
				<el-form-item label="指导价格" prop="priceDeploy">
					<el-input-number v-model="state.priceFrom.priceDeploy" :precision="2" :step="0.1" :min="0.00" :max="5000" />

				</el-form-item>
				<el-form-item label="全套价格" prop="priceGuide">
					<el-input-number v-model="state.priceFrom.priceGuide" :precision="2" :step="0.1" :min="0.00" :max="10000" />

				</el-form-item>
				<el-form-item label="推荐价格比例（%）" prop="priceAccreditRate">
					<el-input-number v-model="state.priceFrom.priceAccreditRate" :precision="2" :step="0.1" :min="0.00"
													 :max="1" />
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="modifyPriceBtn(ruleFormRef)">提交</el-button>
				</div>
			</template>
		</el-dialog>
		<!--		文档查看弹窗-->
		<el-dialog
			v-model="state.viewDialogVisible"
			title="文档"
			width="1180"
		>
			<iframe style="width: 100%;height: 75vh" :src="state.viewDocPath"></iframe>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="state.viewDialogVisible = false">确定</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>
<script setup lang="ts">

import { VideoCamera, Paperclip } from '@element-plus/icons-vue'
import type { TabPaneName, UploadFile, UploadProps,FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import { Plus, UploadFilled } from '@element-plus/icons-vue'
import { postRequest } from '~/composables/http'
import { ProductService } from '~/api/product'
const ruleFormRef = ref<FormInstance>()
const router = useRouter()
const options = reactive({
	width: '100%', //播放器高度
	height: '450px', //播放器高度
	color: "#409eff", //主题色
	title: '', //视频名称
	muted: false, //静音
	webFullScreen: false,
	speedRate: ["0.75", "1.0", "1.25", "1.5", "2.0"], //播放倍速
	autoPlay: false, //自动播放
	loop: false, //循环播放
	mirror: false, //镜像画面
	ligthOff: true,  //关灯模式
	volume: 0.3, //默认音量大小
	control: true, //是否显示控制
	controlBtns:['audioTrack', 'quality', 'speedRate', 'volume', 'setting', 'pip', 'pageFullScreen', 'fullScreen'] //显示所有按钮,
})
const state = reactive(<any>{
	documentList: [],
	imgPath: import.meta.env.VITE_IMG_PATH,
	priceDialogVisible: false,
	viewDialogVisible: false,
	viewDocPath: '',
	docDialogVisible: false,
	priceFrom: {
		productId: '',
		priceCurrentPrice: 0.00,
		priceDeploy: 0.00,
		priceGuide: 0.00,
		priceAccreditRate: 0.00
	},
	docFrom: {},
	pageValidate: {
		pageNo: 1,
		pageSize: 8
	},
	total: 10,
	categorys: '',
	infoDesc: '',
	infoDialogVisible: false,
	userInfoDialogVisible: false,
	dialogVideoVisible: false,
	dialogBzImpsVisible: false,
	localVideoUrl: '',
	bzImpsUrl: '',
	activeName: '上架',
	tabPaneList: ['上架', '下架'],
	queryFrom: {
		name: '',
		type: '',
		productIsPutaway: 1,
		productType: 1
	},
	tableData: [],
	userInfo: {},
	updateFrom: {
		productId: '',
		url: null,
		type: null
	},
	bzImpsFrom: {
		productId: '',
		url: null,
		bzImps: null
	}
})


/**
 * 下载文件
 * @param path
 */
function download(path: any) {
	window.location.href = path
}

/**
 * 删除上传文档
 */
function delDoc(data: any) {
	state.docFrom.createTime = data.createTime
	state.docFrom.fileName = data.fileName
	ProductService.delProductDoc(state.docFrom).then(() => {
		getProductDocInfoList(state.docFrom.productId)

		delete state.docFrom.createTime
		delete state.docFrom.fileName
		toast.success('删除成功')
	})
}

/**
 * 查看文档视图
 * @param url
 */
function view(url: string) {
	const path = 'https://view.xdocin.com/view?src=' + encodeURIComponent(url)
	state.viewDocPath = path
	state.viewDialogVisible = true
}

interface RuleForm {
	priceCurrentPrice: string
	priceDeploy: string
	priceGuide: string
	priceAccreditRate: string

}

const rules = reactive<FormRules<RuleForm>>({
	priceCurrentPrice: [
		{ required: true, message: '价格不能为空', trigger: 'blur' }
	],
	priceDeploy: [
		{ required: true, message: '价格不能为空', trigger: 'blur' }
	],
	priceGuide: [
		{ required: true, message: '价格不能为空', trigger: 'blur' }
	],
	priceAccreditRate: [
		{ required: true, message: '价格不能为空', trigger: 'blur' }
	]
})

/**
 * 价格修改
 */
function updataPrice(data: any) {
	state.priceDialogVisible = true
	state.priceFrom.productId = data.productId
	state.priceFrom.priceCurrentPrice = data.priceCurrentPrice
	state.priceFrom.priceDeploy = data.priceDeploy
	state.priceFrom.priceGuide = data.priceGuide
	state.priceFrom.priceAccreditRate = data.priceAccreditRate
}

/**
 * 价格提交
 * @param formEl
 */
const modifyPriceBtn = async (formEl: FormInstance | undefined) => {
	if (!formEl) return
	await formEl.validate((valid, fields) => {
		if (valid) {
			postRequest('/api/admin/product/updatePrice', state.priceFrom).then(() => {
				state.priceDialogVisible = false
				init()
				toast.success('修改成功')
			})
		}
	})
}

function addProtocol(url) {
	// 如果 URL 已经包含协议，直接返回
	if (/^(http:\/\/|https:\/\/)/.test(url)) {
		return url
	}
	// 否则，添加默认协议（http://）
	return `http://${url}`
}

/**
 * 文档上传成功
 * @param response
 */
const docHandleSuccess: UploadProps['onSuccess'] = (response, uploadFile: UploadFile) => {
	//显示视频
	state.docFrom.path = response.data.url
	state.docFrom.name = uploadFile.name.toString().split('.')[0]
}

//添加文档
function document(data: any) {
	//添加文档
	state.docFrom.productId = data.productId
	getProductDocInfoList(state.docFrom.productId)
	state.docDialogVisible = true
}

/**
 * 文档上传提交
 */
function docBtn() {
	if (state.docFrom.productId == '' || state.docFrom.productId == undefined) {
		toast.error('商品编号不能为空')
		return
	}
	if (state.docFrom.path == '' || state.docFrom.path == undefined) {
		toast.error('文档不能为空')
		return
	}
	if (state.docFrom.name == '' || state.docFrom.name == undefined) {
		toast.error('文档名称不能为空')
		return
	}
	postRequest('/api/admin/file/document', state.docFrom).then(() => {
		toast.success('上传成功')
		delete state.docFrom.name
		delete state.docFrom.path
		getProductDocInfoList(state.docFrom.productId)
	})
}

function getProductDocInfoList(productId: number) {
	ProductService.getProductInfo({ productId: productId }).then(res => {
		state.documentList = res.data.documentList
	})
}

/**
 * 初始化
 */
function init() {
	postRequest('/api/admin/product/searchProductAdmin', {
		pageValidate: { pageValidate: state.pageValidate },
		params: state.queryFrom
	}).then((res: any) => {
		state.tableData = res.data.lists
		state.total = res.data.count
		state.pageValidate.pageSize = res.data.pageSize
		state.pageValidate.pageNo = res.data.pageNo
	})
}

/**
 * 修改视频或者B站引用 signGengw()
 */
function updataFile() {
	if (state.updateFrom.url === null) {
		toast.error('商品编号或者文件不能为空')
		return
	}
	postRequest('/admin/product/ProductFileUpdateAdmin', state.updateFrom).then((res: any) => {
		if (res.code === 200) {
			toast.success('修改成功')
			state.dialogVideoVisible = false
			state.dialogBzImpsVisible = false
			state.updateFrom = {}
			init()
		} else {
			toast.error(res.msg)
		}
	})


}

function updataBzImps() {
	if (state.bzImpsFrom.bzImps === null) {
		toast.error('商品编号或者B站引用不能为空')
		return
	}
	postRequest('/admin/product/ProductFileBImpsUpdateAdmin', state.bzImpsFrom).then((res: any) => {
		if (res.code === 200) {
			toast.success('修改成功')
			state.dialogVideoVisible = false
			state.dialogBzImpsVisible = false
			state.updateFrom = {}
			init()
		} else {
			toast.error(res.msg)
		}
	})

}

const videoHandleSuccess: UploadProps['onSuccess'] = (response) => {
	//显示视频
	state.updateFrom.url = response.data.url
}

function video(data: any) {
	state.dialogVideoVisible = true
	state.updateFrom.url = data.videoFiles
	state.updateFrom.productId = data.productId
	state.updateFrom.type = 1
}

function bzImps(data: any) {
	state.dialogBzImpsVisible = true
	state.bzImpsFrom.bzImps = data.bzImps
	state.bzImpsFrom.productId = data.productId
	state.bzImpsFrom.type = 3
}

/**
 * 删除商品
 * @param val
 */
function del(val: any) {
	postRequest('/admin/product/delProductAdmin', { 'productId': val.productId }).then((res: any) => {
		if (res.code === 200) {
			toast.success('商品删除成功')
			init()
		}
	})
}


/**
 * 详情页跳转
 * @param id
 */
function to(id: any) {
	router.push(`/product/${id}`)
}

/**
 * 用户信息
 * @param data
 */
function userInfo(data: any) {
	state.userInfo = data
	state.userInfoDialogVisible = true
}

const handleCurrentChange = (val: number) => {
	state.pageValidate.pageNo = val
	init()
}

init()

function info(data: string) {
	state.infoDialogVisible = true
	state.infoDesc = data
}

function handleClose() {
	state.infoDesc = ''
	state.infoDialogVisible = false
}

/**
 * 下架商品
 * @param data
 * @param status
 */
function offShelf(data: any, status: number) {
	let updateParams = {
		productId: data.productId,
		productIsPutaway: status
	}
	postRequest('/api/admin/product/updateProductAdmin', updateParams).then((res: any) => {
		if (res.code === 200) {
			if (status === 0) {
				toast.success('商品已经下架')
			} else {
				toast.success('商品已经上架')
			}
			init()
		}
	})
}


/**
 * 审核函数 start
 * @param status
 */
// function getTagType(status: any) {
//   switch (status) {
//     case 0:
//       return 'info'; // 待审核
//     case 1:
//       return 'success'; // 审核通过
//     case 2:
//       return 'danger'; // 审核拒绝
//     default:
//       return 'default';
//   }
// }
//
// function getAuditStatusText(status: any) {
//   switch (status) {
//     case 0:
//       return '待审核';
//     case 1:
//       return '审核通过';
//     case 2:
//       return '审核拒绝';
//     default:
//       return '未知状态';
//   }
// }

/**
 * 审核函数 end
 */



//标签页点击
const handleClick = (name: TabPaneName) => {
	if (name === '下架') {
		state.queryFrom.productIsPutaway = 0
		init()
	} else if (name === '上架') {
		state.queryFrom.productIsPutaway = 1
		init()
	}

}

</script>
<style scoped>
.top {
	margin-bottom: 10px;
}

.pagination-container {
	display: flex;
	justify-content: center;
	margin-top: 20px; /* 可根据需要调整外边距 */
}

:deep(iframe) {
	width: 100%;
	height: 300px;
}

.doc-upload {
	width: 100%;
	height: 200px;
}
</style>
